#include "colorwheel.h"
#include <QMouseEvent>
#include <QPainter>
#include <QDebug>

ColorWheel::ColorWheel(QWidget *parent) :
   QFrame(parent)
{
   setMouseTracking(true);
   mFilename = ":/res/gfx/colorwheel2.png";
   mMovingIndicator = false;

   mColorWheelImage.load(mFilename);
   mIndicatorPosition.setX(mColorWheelImage.size().width()/2);
   mIndicatorPosition.setY(mColorWheelImage.size().height()/2);

   mSelectedColor.setRgb(255,0,0);
}

void ColorWheel::mousePressEvent(QMouseEvent* event)
{
   mMovingIndicator = true;
   mIndicatorPosition = event->pos();
   setTempColor(QColor(mColorWheelImage.pixel(event->pos())));
   update();
   //qDebug() << "ColorWheel::mousePressEvent" << event->pos();
}

void ColorWheel::mouseReleaseEvent(QMouseEvent* event)
{
   mSelectedColor = QColor(mColorWheelImage.pixel(event->pos()));
   emit newColorSelected(mSelectedColor);

   mMovingIndicator = false;
   mIndicatorPosition = event->pos();
   //qDebug() << "ColorWheel::mouseReleaseEvent" << event->pos();
   QString ss = "background-color: rgb(";
   ss += QString::number(mSelectedColor.red());
   ss += ", ";
   ss += QString::number(mSelectedColor.green());
   ss += ", ";
   ss += QString::number(mSelectedColor.blue());
   ss += ");";
   parentWidget()->setStyleSheet(ss);
}

void ColorWheel::mouseMoveEvent(QMouseEvent *event)
{
   if (mMovingIndicator)
   {
      mIndicatorPosition = event->pos();
      setTempColor(QColor(mColorWheelImage.pixel(event->pos())));
   }
}

void ColorWheel::paintEvent(QPaintEvent *paintEvent)
{
   QFrame::paintEvent(paintEvent);
   QPainter painter(this);
   QPen pen(Qt::black);
   painter.setPen(pen);
   painter.drawEllipse(mIndicatorPosition, 3,3);
   //qDebug() << "ColorWheel::paintEvent pos=" << mIndicatorPosition;
}


void ColorWheel::setTempColor(const QColor &color)
{
   QString ss = "background-color: rgb(";
   ss += QString::number(color.red());
   ss += ", ";
   ss += QString::number(color.green());
   ss += ", ";
   ss += QString::number(color.blue());
   ss += ");\n";
   ss += "background-image: url(";
   ss += mFilename;
   ss += ");";
   //qDebug() << "ColorWheel::setTempColor" << ss;
   setStyleSheet(ss);
}

QColor ColorWheel::selectedColor()
{
   return mSelectedColor;
}
